﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Noria.Web.MyMSDN.Models;
using File = Noria.Web.MyMSDN.Models.File;

namespace Noria.Web.Utility
{
    /// <summary>
    /// Summary description for import
    /// </summary>
    public class ImportHandler : IHttpHandler
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public void ProcessRequest(HttpContext context)
        {
            var root = context.Server.MapPath("tmp");
            foreach (var json in Directory.GetFiles(root, "*.json"))
            {
                var buffer = System.IO.File.ReadAllText(json);
                var files = JsonConvert.DeserializeObject<File[]>(buffer);

                using (var db = new MmContext())
                {
                    foreach (var file in files)
                    {
                        db.Files.Add(file);
                    }
                    db.SaveChanges();
                    log.Info(json + " imported.");
                }
            }

            log.Info("ImportHandler completed.");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}